#pragma once

#include "../QDrawCell/qbasedrawcell.h"
#include "../QDraw.h"
#include "../QMath/qmath.h"

#include <map>
#include <vector>

QNamespaceStart(Qui)

class QWidget
{
	private:
		qsize_t control_id = 0;

		HWND    widget_handle;

	private:
		std::map<qsize_t, QDrawCellBase*> control_map;

	public:
		virtual void move_repaint(qsize_t id, QSize_t new_space, QSize_t old_space, qsize_t* new_id, bool draw,
			QDrawCellBase* event_sender)
		{
			auto move_object      = control_map.find(id);

			BeginBatchDraw();

			setfillcolor(getbkcolor());

			QSize_t compare_size;

			QDrawFillRectangle(old_space.x - 1, old_space.y - 1, 
					old_space.x + old_space.width + 1, old_space.y + old_space.height + 1);
			QDrawFillRectangle(new_space.x - 1, new_space.y - 1, 
					new_space.x + new_space.width + 1, new_space.y + new_space.height + 1);

			if (draw == true)
			{
				move_object.operator*().second
					->draw();
			}

			for (auto item = control_map.begin(); item != control_map.end();
					++item)
			{
				compare_size = item.operator*().second->get_size();

				if ((QRectIntersection(old_space, compare_size) ||
					QRectIntersection(new_space , compare_size)) && item != move_object)
				{
					item.operator*().second->draw();
				}
			}

			FlushBatchDraw();

			++control_id;

			control_map.insert(std::pair<qsize_t, QDrawCellBase*>
					(control_id, event_sender));
			control_map.erase(id);

			if (new_id != nullptr)
			{
				*new_id = control_id;
			}

			EndBatchDraw();
		}

	public:
		QWidget(int width, int height, int easyx_control_code = 0x0)
		{
			widget_handle = initgraph(width, height, easyx_control_code);

			hide();
		}

	public:
		void hide()
		{
			ShowWindow(widget_handle, SW_HIDE);
		}
		void show()
		{
			ShowWindow(widget_handle, SW_SHOW);
		}

	public:
		void bind_contorl(QDrawCellBase* control, qsize_t* id)
		{
			control_map.insert(std::pair<qsize_t, QDrawCellBase*>(control_id, control));

			if (id != nullptr)
			{
				*id = control_id;
			}

			++control_id;
		}

		QUNUSED
			qsize_t get_id_by_object(QDrawCellBase* object)
		{
			for (std::map<qsize_t, QDrawCellBase*>::iterator item = control_map.begin(); 
					item != control_map.end(); ++item)
			{
				if (item.operator*().second == object)
				{
					return item.operator*().first;
				}
			}

			return -1;
		}
};

QNamespaceEnd